package com.dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import com.entity.File;
import com.util.DBHelp;
import com.util.RowMapper;

public class FileDao {
	
	DBHelp<File> help=new DBHelp<File>();

	public List<File> getAll() {
		String sql="SELECT `id`,`name`,`filename`,`filesize`,`createtime`,`fileTypeid`,`employeeid` FROM `t_file` ORDER BY `createtime` DESC";
		return help.executeQueryForList(sql, new Mapper());
	}
	
	public void add(File f) {
		String sql="INSERT INTO `t_file`(`id`,`name`,`filename`,`filesize`,`createtime`,`fileTypeid`,`employeeid`) VALUES(?,?,?,?,?,?,?)";
		help.executeSQL(sql, f.getId(),f.getName(),f.getFilename(),f.getFilesize(),f.getCreatetime(),f.getFileTypeid(),f.getEmployeeid());
	}
	
	public File getById(String id) {
		String sql="SELECT `id`,`name`,`filename`,`filesize`,`createtime`,`fileTypeid`,`employeeid` FROM `t_file` WHERE id=?";
		return help.executeQueryForObject(sql, new Mapper(), id);
	}
	
	public void deleteById(String id) {
		String sql="DELETE FROM `t_file` WHERE id=?";
		help.executeSQL(sql, id);
	}
	
	public long getSizeById(String id) {
		String sql="SELECT SUM(`filesize`) FROM `t_file` WHERE `fileTypeid`='"+id+"'";
		String size=help.query(sql);
		if (size==null||"".equals(size)) {
			size="0";
		}
		return Long.parseLong(size);
	}
	
	public int getNum(String id) {
		String sql="SELECT COUNT(`id`) FROM `t_file` WHERE `fileTypeid`='"+id+"'";
		String num=help.query(sql);
		if (num==null||"".equals(num)) {
			num="0";
		}
		
		return Integer.parseInt(num);
	}
	
	public void deleteByFTId(String id) {
		String sql="DELETE FROM `t_file` WHERE `fileTypeid`=?";
		help.executeSQL(sql, id);
	}
	
	private class Mapper implements RowMapper<File>{

		public File mapperRow(ResultSet rs) throws SQLException {
			File file=new File();
			file.setCreatetime(rs.getString("createtime"));
			file.setEmployeeid(rs.getString("employeeid"));
			file.setFilename(rs.getString("filename"));
			file.setFilesize(rs.getString("filesize"));
			file.setFileTypeid(rs.getString("fileTypeid"));
			file.setId(rs.getString("id"));
			file.setName(rs.getString("name"));
			
			return file;
		}
		
	}

}
